package cn.lzwei.bilimall.product.service.impl;

import cn.lzwei.bilimall.product.entity.*;
import cn.lzwei.bilimall.product.feign.CouponFeignService;
import cn.lzwei.bilimall.product.service.*;
import cn.lzwei.bilimall.product.vo.*;
import cn.lzwei.common.to.BoundsTo;
import cn.lzwei.common.to.FullReductionTo;
import cn.lzwei.common.utils.R;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.lzwei.common.utils.PageUtils;
import cn.lzwei.common.utils.Query;

import cn.lzwei.bilimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.comparator.ComparableComparator;
import org.springframework.util.comparator.Comparators;

import javax.annotation.Resource;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Resource
    SpuInfoDescService spuInfoDescService;
    @Resource
    SpuImagesService spuImagesService;
    @Resource
    ProductAttrValueService productAttrValueService;
    @Resource
    AttrService attrService;
    @Resource
    SkuInfoService skuInfoService;
    @Resource
    SkuSaleAttrValueService skuSaleAttrValueService;
    @Resource
    SkuImagesService skuImagesService;
    @Resource
    CouponFeignService couponFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }
    /**
     * TODO 高级部分完善
     * 保存spu、sku信息：新增商品
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        //1.保存spu基本信息 pms_spu_info：id  spu_name  spu_description  catalog_id  brand_id  weight  publish_status  create_time  update_time
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.save(spuInfoEntity);
        Long spuId = spuInfoEntity.getId();

        //2.保存spu介绍 pms_spu_info_desc： spu_id  decript
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuId);
        List<String> decript = spuSaveVo.getDecript();
        spuInfoDescEntity.setDecript(String.join(",",decript));
        spuInfoDescService.save(spuInfoDescEntity);

        //3.保存spu图集 pms_spu_images：  id  spu_id  img_name  img_url  img_sort  default_img
        List<String> images = spuSaveVo.getImages();
        List<SpuImagesEntity> spuImagesEntities = images.stream().map(item -> {
            SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
            spuImagesEntity.setSpuId(spuId);
            spuImagesEntity.setImgUrl(item);
            return spuImagesEntity;
        }).collect(Collectors.toList());
        spuImagesService.saveBatch(spuImagesEntities);

        //4.保存积分信息 （远程服务）sms_spu_bounds： id  spu_id  grow_bounds  buy_bounds    work
        Bounds bounds = spuSaveVo.getBounds();
        BoundsTo boundsTo = new BoundsTo();
        BeanUtils.copyProperties(bounds,boundsTo);
        boundsTo.setSpuId(spuId);
        R r = couponFeignService.saveBounds(boundsTo);
        if (r.getCode()!=0){
            log.error("远程调用失败!");
        }

        //5.保存规格参数 pms_product_attr_value：    id  spu_id  attr_id  attr_name  attr_value  attr_sort  quick_show
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map(item -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setSpuId(spuId);
            productAttrValueEntity.setAttrId(item.getAttrId());
            AttrEntity attrEntity = attrService.getById(item.getAttrId());
            productAttrValueEntity.setAttrName(attrEntity.getAttrName());
            productAttrValueEntity.setAttrValue(item.getAttrValues());
            productAttrValueEntity.setQuickShow(item.getShowDesc());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(productAttrValueEntities);

        //6.sku信息：
        List<Skus> skus = spuSaveVo.getSkus();
        for (Skus sku : skus) {
            //6.1、保存sku基本信息 pms_sku_info：sku_id  spu_id  sku_name  sku_desc  catalog_id  brand_id  sku_default_img  sku_title  sku_subtitle  price   sale_count
            String defaultImg="";
            for (Images image : sku.getImages()) {
                if (image.getDefaultImg()==1) defaultImg=image.getImgUrl();
            }
            SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
            BeanUtils.copyProperties(sku,skuInfoEntity);
            skuInfoEntity.setSpuId(spuId);
            List<String> descar = sku.getDescar();
            skuInfoEntity.setSkuDesc(String.join(",",descar));
            skuInfoEntity.setCatalogId(spuSaveVo.getCatalogId());
            skuInfoEntity.setBrandId(spuSaveVo.getBrandId());
            skuInfoEntity.setSkuDefaultImg(defaultImg);
            skuInfoEntity.setSaleCount(0l);
            skuInfoService.save(skuInfoEntity);
            Long skuId = skuInfoEntity.getSkuId();

            //6.2、保存sku销售属性 pms_sku_sale_attr_value：   id  sku_id  attr_id  attr_name  attr_value  attr_sort
            List<Attr> attrs = sku.getAttr();
            List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attrs.stream().map(item -> {
                SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                skuSaleAttrValueEntity.setSkuId(skuId);
                BeanUtils.copyProperties(item,skuSaleAttrValueEntity);
                skuSaleAttrValueEntity.setAttrSort(0);
                return skuSaleAttrValueEntity;
            }).collect(Collectors.toList());
            skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

            //6.3、保存sku图集 pms_sku_images：    id  sku_id  img_url  img_sort  default_img
            List<Images> imgs = sku.getImages();
            List<SkuImagesEntity> skuImagesEntities = imgs.stream().map(item -> {
                SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                BeanUtils.copyProperties(item,skuImagesEntity);
                skuImagesEntity.setSkuId(skuId);
                skuImagesEntity.setImgSort(0);
                return skuImagesEntity;
            }).filter(item->{
                //过滤空图片
                return !StringUtils.isNullOrEmpty(item.getImgUrl());
            }).collect(Collectors.toList());
            skuImagesService.saveBatch(skuImagesEntities);

            //6.4、保存打折、满减、会员优惠信息 （远程服务） sms_sku_ladder、sms_sku_full_reduction、sms_member_price
            FullReductionTo fullReductionTo = new FullReductionTo();
            fullReductionTo.setSkuId(skuId);
            BeanUtils.copyProperties(sku,fullReductionTo);
            //如果存在打折优惠或者满减优惠再进行保存
            if(sku.getFullCount()>0 || sku.getFullPrice().compareTo(new BigDecimal(0))==1){
                R r1 = couponFeignService.saveTotal(fullReductionTo);
                if(r1.getCode()!=0){
                    log.error("远程调用失败！");
                }
            }
        }
    }
    /**
     * spu检索列表：模糊查询、分类、品牌、状态
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        //1.状态
        String status = (String) params.get("status");
        if (!StringUtils.isNullOrEmpty(status)){
            queryWrapper.eq("publish_status",status);
        }
        //2.模糊查询
        String key = (String) params.get("key");
        if (!StringUtils.isNullOrEmpty(key)){
            queryWrapper.and(item->{
                item.eq("id",key).or().like("spu_name",key);
            });
        }
        //3.品牌
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isNullOrEmpty(brandId) && !"0".equals(brandId)){
            queryWrapper.eq("brand_id",brandId);
        }
        //4.分类
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isNullOrEmpty(catelogId) && !"0".equals(catelogId)){
            queryWrapper.eq("catalog_id",catelogId);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

}